package com.sky.service.impl;

import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.NoExistException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {
	@Autowired
	private CategoryMapper categoryMapper;

	@Autowired
	private DishMapper dishMapper;
	/**
	 * 根据类型查询分类
	 * @return
	 */
	@Override
	public List<Category> list(Integer type) {
		List<Category> lc = categoryMapper.list(type);
		if(lc == null){
			throw new NoExistException();
		}
		return lc;
	}

	@Override
	public PageResult page(CategoryPageQueryDTO categoryPageQueryDTO) {
		PageResult pageResult = new PageResult();
		//查询菜品分类总个数
		Integer total = categoryMapper.total();
		log.info("菜品分类总数:{}",total);
		//计算起始记录
		Integer page = categoryPageQueryDTO.getPage();
		Integer pageSize = categoryPageQueryDTO.getPageSize();
		Integer starter = (page - 1) * pageSize;
		categoryPageQueryDTO.setPage(starter);
		log.info("limit starter:{}, pageSize:{}",starter,pageSize);
		//分页查询菜品
		List<Category> lc = categoryMapper.page(categoryPageQueryDTO);
		//封装结果
		pageResult.setTotal(total);
		pageResult.setRecords(lc);
		log.info("查询结果:{}",lc);
		return pageResult;
	}

	@Override
	@Transactional
	public void setStatus(Category category) {
		categoryMapper.setStatus(category);
	}

	@Override
	@Transactional
	public void add(CategoryDTO categoryDTO) {
		Category category = new Category();
		//填充字段
		BeanUtils.copyProperties(categoryDTO, category);
		//默认禁用菜品分类
		category.setStatus(0);
		log.info("新增菜品分类类型:{}",category);
		categoryMapper.add(category);
	}

	@Override
	@Transactional
	public void deleteById(Long id) {
		log.info("删除id为{}的菜品分类",id);
		//检测是否有该分类的菜品
		Integer counts_dish = dishMapper.dishCountByCategoryId(id);
		log.info("当前分类下菜品个数:{}",counts_dish);
		//如有,删除失败
		if(counts_dish > 0){
			log.info("当前分类下还有菜品,非法操作!");
			throw new DeletionNotAllowedException("当前分类下还有菜品!!!");
		}
		categoryMapper.deleteById(id);
	}

	@Override
	public void edit(CategoryDTO categoryDTO) {
		Category category = new Category();
		//填充字段
		BeanUtils.copyProperties(categoryDTO, category);
		//查询菜品类型回填
		Integer type = categoryMapper.type(category.getId());
		log.info("查询菜品类型{}",type);
		category.setType(type);
		log.info("category:{}", category);
		categoryMapper.edit(category);
	}
}
